package servlets;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Item;
import model.User;

import dao.ItemManager;

@WebServlet("/items")
public class ItemsServlet extends HttpServlet
{
    private static final long serialVersionUID = 1L;

    private ItemManager itemManager;

    @Override
    public void init(ServletConfig config) throws ServletException
    {
	super.init(config);
	this.itemManager = new ItemManager();
    }

    @Override
    public void destroy()
    {
	this.itemManager = null;
	super.destroy();
    }

    protected void doPost(HttpServletRequest request,
	    HttpServletResponse response) throws ServletException, IOException
    {

	HttpSession session = request.getSession(true);
	String title = request.getParameter("title");
	String author = request.getParameter("author");
	String publishDate = request.getParameter("publishDate");
	String owner = ((User) session.getAttribute("user")).getUsername();
	String type = request.getParameter("type");
	
	int maxPeriod = 14;
	try{
	maxPeriod=Integer.parseInt(request.getParameter("maxPeriod"));
	}catch(Exception e){
	    
	}
	String message = null;
	if (request.getParameter("edit") != null)
	{
	    int id=Integer.parseInt(request.getParameter("id"));
	    boolean productUpdated = this.itemManager.updateItem(id, title, author, publishDate, type, maxPeriod);
	    if (productUpdated)
	    {
		message = "The item was updated successfully.";
	    } else
	    {
		message = "There was an error updating the item. Please try again.";
	    }
	    
	}
	if (request.getParameter("add") != null)
	{
	    boolean productInserted = this.itemManager.insertItem(title,
		    author, publishDate, owner, type, maxPeriod);
	    if (productInserted)
	    {
		message = "The item was inserted successfully.";
	    } else
	    {
		message = "There was an error inserting the item. Please try again.";
	    }
	}

	List<Item> allItems = this.itemManager.fetchOwnFreeItems(owner);
	session.setAttribute("items", allItems);
	session.setAttribute("message", message);
	response.sendRedirect("items.jsp");
	return;
    }
}
